import { ConfigService } from '@nestjs/config';
import { config } from 'dotenv';
import { DataSource } from 'typeorm';

async function initEmptyDatabase() {
  // Load environment variables
  config();
  const configService = new ConfigService();

  // Use migration-specific database name
  const dbName = 'api_webservice_migration';

  console.log(`Initializing empty database for migration generation: ${dbName}`);

  // Create a temporary connection to postgres database
  const tempDataSource = new DataSource({
    type: 'postgres',
    host: configService.get('DB_HOST'),
    port: parseInt(configService.get('DB_PORT') || '5432'),
    username: configService.get('DB_USERNAME'),
    password: configService.get('DB_PASSWORD'),
    database: 'postgres', // Connect to default postgres database first
  });

  try {
    await tempDataSource.initialize();
    console.log('Connected to PostgreSQL server');

    // Ensure uuid extension is available
    await tempDataSource.query(`
      CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    `);
    console.log('Ensured uuid-ossp extension is available');

    // Check if the database exists and drop it if it does
    const dbCheckResult = await tempDataSource.query(
      `SELECT 1 FROM pg_database WHERE datname = '${dbName}'`,
    );

    if (dbCheckResult.length > 0) {
      console.log(`Database ${dbName} exists, dropping it to start fresh...`);

      // Kill active connections to the database to allow dropping it
      await tempDataSource.query(`
        SELECT pg_terminate_backend(pid)
        FROM pg_stat_activity
        WHERE datname = '${dbName}';
      `);

      // Drop the database
      await tempDataSource.query(`DROP DATABASE ${dbName};`);
      console.log(`Database ${dbName} dropped successfully`);
    }

    // Create the database
    await tempDataSource.query(`CREATE DATABASE ${dbName};`);
    console.log(`Empty database ${dbName} created successfully`);

    // Close temporary connection
    await tempDataSource.destroy();
    console.log('Empty database initialization completed successfully');
  } catch (error) {
    console.error('Error initializing empty database:', error);
    process.exit(1);
  }
}

// Run the initialization function
// initEmptyDatabase();
